'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/dlsgyyj/compute 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let jstime1 = new Date().getTime();

		var dailishangzongjinelist = [];
		var dailishangzongjinelist1 = [];
		var dailishanglist = [];
		var pay_rs_num = [];
		var pay_bs_num = [];
		var commission_rate_list = [];
		var commission_rate_list1 = [];
		const $ = _.aggregate;

		let {
			lastMonthStart,
			lastMonthEnd,
		} = vk.pubfn.getCommonTime(new Date());

		var lastMonth = vk.pubfn.timeFormat(lastMonthStart, "yyyy-MM");

		//查询数据库的a_datas表中是否已存在上个月的代理佣金数据
		let lastMonth_data = await db.collection('a_datas').where({
			month: lastMonth,
			type: 8,
		}).count();
		console.log("lastMonth_data", lastMonth_data.total);
		//如果存在直接终止函数的执行
		if (lastMonth_data.total > 0) {
			return res;
		};

		//获取代理商的的用户数据
		var results = await db.collection('uni-id-users').where({
			role: _.in(["agent"])
		}).get();
		dailishanglist = results.data;
		console.log("代理商的用户列表=>", dailishanglist);

		//获取上个月代理商的引流金额
		for (var i = 0; i <= dailishanglist.length - 1; i++) {
			dailishangzongjinelist[i] = await db.collection('a_recharge').aggregate().match({
				_add_time: _.and(_.gte(lastMonthStart), _.lte(lastMonthEnd)),
				invite_code: dailishanglist[i]._id,
			}).group({
				_id: null,
				totalPrice: $.sum('$shifu_amount')
			}).end();
			console.log("dailishangzongjinelist=", dailishangzongjinelist);
		};
		console.log("daishangzongjinelist=>", dailishangzongjinelist);
		//获取上个月代理商的引流金额换算后的数据
		for (var i = 0; i <= dailishangzongjinelist.length - 1; i++) {
			if (dailishangzongjinelist[i].data.length == 0) {
				dailishangzongjinelist1[i] = 0;
			} else {
				dailishangzongjinelist1[i] = dailishangzongjinelist[i].data[0].totalPrice / 100;
			};
		};
		console.log("换算后的数据=>", dailishangzongjinelist1);
		//获取付费人数
		for (var i = 0; i <= dailishanglist.length - 1; i++) {
			let Recharges = await vk.baseDao.select({
				dbName: "a_recharge", // 表名
				getCount: true, // 是否需要同时查询满足条件的记录总数量，默认false
				getMain: false, // 是否只返回rows数据，默认false
				pageIndex: 1, // 当前第几页
				pageSize: -1, // 每页条数
				// 只要user_id字段
				fieldJson: {
					user_id: true,
				},
				whereJson: {
					pay_status: 1,
					_add_time: _.and(_.gt(lastMonthStart), _.lt(lastMonthEnd)),
					invite_code: dailishanglist[i]._id,
				}
			});
			//获取付费笔数
			pay_bs_num[i] = Recharges.total;
			//从数组中提取user_id字段形式新的数组
			let rows = vk.pubfn.arrayObjectGetArray(Recharges.rows, "user_id");
			//一个用户可能充值多次，因此需要去重
			let newRows = [...new Set(rows)]; //利用了Set结构不能接收重复数据的特点进行去重
			console.log("newRows.length=", newRows.length);
			//获取付费人数
			pay_rs_num[i] = newRows.length;
		};
		console.log("获取付费人数");
		//获取佣金比例
		for (var i = 0; i <= dailishanglist.length - 1; i++) {
			commission_rate_list[i] = await db.collection('a_agent_grade').where({
				_id: dailishanglist[i].agent_id,
			}).field({
				'commission_rate': true,
			}).get();
			if (commission_rate_list[i].data.length == 0) {
				commission_rate_list1[i] = 0;
			} else {
				commission_rate_list1[i] = commission_rate_list[i].data[0].commission_rate;
			};
		};
		console.log("获取佣金比例", commission_rate_list1);
		//添加数据到数据库中
		for (var i = 0; i <= dailishanglist.length - 1; i++) {
			let add_datas = await db.collection('a_datas').add({
				month: lastMonth || "2023",
				agent_username: dailishanglist[i].username,
				agent_nickname: dailishanglist[i].nickname,
				agent_id: dailishanglist[i]._id,
				pay_rs_num: pay_rs_num[i],
				pay_bs_num: pay_bs_num[i],
				pay_je_num: dailishangzongjinelist1[i],
				yj_bl: commission_rate_list1[i],
				kn_yj: dailishangzongjinelist1[i] * commission_rate_list1[i],
				type: 8, //0是平台总数据，1是账号级数据，2是链接级数据
				_add_time: new Date().getTime(),
				_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
			});
			console.log("添加代理商上个月的佣金情况数据==》", add_datas);
		};
		console.log("添加数据到数据库中");
		let jstime2 = new Date().getTime();
		console.log("共耗时：", jstime2 - jstime1);
		res.msg = "结束";

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
